# -*- coding: UTF-8 -*-

import demjson
import requests

'''
通过接口的方式获取数据，并截取想要的原始数据

url : 接口地址
params : 接口的入参
start_str : 接口返回值中前端要删除的部分
end_str : 接口返回值中后端要删除的部分

get_response() : 返回dict类型的数据
'''

class DataInterface(object):

    def __init__(self, url, params, start_str, end_str):

        self.url = url
        self.params = params
        self.start_str = start_str
        self.end_str = end_str
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
        }

    def get_response(self, key):

        # 返回的值不是json格式，无法直接使用r.json()方法转换返回值的格式
        response = requests.get(self.url, params=self.params, headers=self.headers)
        data_str = response.text.lstrip(self.start_str).rstrip(self.end_str)
        # demjson.decode() 返回dict类型，demjson.encode() 返回string类型
        # demjson.decode() 解决 字符串中的key值没有引号 的问题
        dic_data = demjson.decode(data_str)
        return dic_data[key]

    def post_response(self):
        pass


if __name__ == '__main__':

    url = 'http://fund.eastmoney.com/data/rankhandler.aspx'

    sd = '2019-01-01'
    ed = '2019-12-31'
    pn = 50

    params = {
        "op": "ph",  # ph-排行
        "dt": "kf",  # kf-开放
        "ft": "all",  # all-所有
        "rs": "",
        "gs": 0,
        "sc": "zzf",  # 按哪一行排序  zzf-???
        "st": "desc",
        "sd": sd,  # sd-查询的开始日期 "2019 - 02 - 19"
        "ed": ed,  # all-查询的结束日期 "2020 - 02 - 19"
        "qdii": "",
        "tabSubtype": ["", "", "", "", "", ""],
        "pi": 1,  # pi-第几页
        "pn": pn,  # pn-1页展示的条数
        "dx": 1,
        "v": 0.8367023148607453
    }

    start_str = 'var rankData = '
    end_str = ';'

    ifp = DataInterface(url, params, start_str, end_str)

    str_data = ifp.get_response('datas')
    print(str_data)
    print('-------------------------------------------------------------')


    callback = 'jQuery18308791608443714658_1582188591207'
    parament = '1582188591226'

    url2 = 'http://fund.eastmoney.com/api/Dtshph.ashx'

    params2 = {
        "t": 2,  # 全部基金-0, 股票型-1, 混合型-2, 债券型-3, 指数型-4, QDII-5
        "c": "yndt",  # 按那列数值排序, dwjz-按单位净值, yndt-按一年定投
        "s": "desc",  # 排序, 降序-desc
        "issale": 1,  # 可购-1, 全部-0
        "page": 1,  # 当前展示页的页数
        "psize": 20,  # 分页-100, 不分页-20000
        "callback": callback,
        "_": parament
    }

    start_str2 = callback + '('  # 'jQuery18306380296455617336_1582286095728('
    end_str2 = ')'

    ifi = DataInterface(url2, params2, start_str2, end_str2)
    str_data2 = ifi.get_response('data')
    print(str_data2)